#include "makuai.h"
#include "onewire.h"
#include "ds1302.h"

unsigned char code ds_write_arr[3] = {0x80,0x82,0x84},ds_read_arr[3] = {0x81,0x83,0x85};
unsigned char ds1302_time[3] = {0x00,0x25,0x23};
unsigned char time_count = 0,T_can = 23,show_mode = 0;
static unsigned char Key_Number = 0,t_mode = 0,k_count = 0;
unsigned short t_count = 999,T = 0;
float t1 = 0.0;

void Timer2Init(void)		//500微秒@12.000MHz
{
	AUXR |= 0x04;		//定时器时钟1T模式
	T2L = 0x90;		//设置定时初值
	T2H = 0xE8;		//设置定时初值
	EA = 1;
	IE2 |= 0x04;
	AUXR |= 0x10;		//定时器2开始计时
}

void ds1302_settime(void)
{
	unsigned char time1 = 0;
	Write_Ds1302_Byte(0x8e,write_off);
	for(time1=0;time1<3;time1++)
	{
		Write_Ds1302_Byte(ds_write_arr[time1],ds1302_time[time1]);
	}
	Write_Ds1302_Byte(0x8e,write_on);
}

void read_ds(void)
{
	unsigned char time2 = 0;
	for(time2=0;time2<3;time2++)
	{
		ds1302_time[time2] = Read_Ds1302_Byte(ds_read_arr[time2]);
	}
}

void can_show(void)
{
	while(show_mode == 2)
	{
		if(k_count == 10)
		Key_Number = Key();
		if(Key_Number == 15)
			show_mode = 0;
		if(Key_Number == 16)
			T_can++;
		if(Key_Number == 12)
			T_can--;
		if(T>T_can)
		Latch(RELAY,0xff);
	else
		Latch(RELAY,0x00);
	Nixie(1,21);
	Nixie(2,3);
	Nixie(7,T_can/10);
	Nixie(8,T_can%10);
	}
}

void time_show(void)
{
	while(show_mode == 1)
	{
		if(k_count == 10)
		Key_Number = Key_time();
		if(Key_Number == 15)
			show_mode++;
		Nixie(1,21);
		Nixie(2,2);
		Nixie(4,ds1302_time[2]/16);
		Nixie(5,ds1302_time[2]%16);
		Nixie(7,ds1302_time[1]/16);
		Nixie(8,ds1302_time[1]%16);
	if(time_count = 18)
		read_ds();
	
}
}

void t_show(void)
{
	while(show_mode == 0)
	{
		if(k_count == 10)
		Key_Number = Key();
		if(Key_Number == 15)
			show_mode++;
	if(t_mode)
		ds_inti();
	if(!t_mode)
	{
		t1 = t_return();
		T = (unsigned int)t1;
	}
	if(T>T_can)
		Latch(RELAY,0xff);
	else
		Latch(RELAY,0x00);
		Nixie(1,21);
		Nixie(2,1);
		Nixie(7,T/10);
		Nixie(8,T%10);
}
}


void main(void)
{
	Latch(RELAY,0x00);
	ds1302_settime();
	ds_inti();
	Delay(700);
	Latch(LED,0xaa);
	Timer2Init();
	while(1)
	{
		t_show();
		time_show();
		can_show();
	}
}

void timer2() interrupt 12 using 1
{
	T2L = 0x90;		//设置定时初值
	T2H = 0xE8;		//设置定时初值
	if(++t_count == 1000)
	{
		t_count = 0;
		t_mode ^= 1;
	}
	if(++k_count == 12)
		k_count = 0;
	if(++time_count == 20)
		time_count = 0;
}
